<template>
  <div class="member-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="超级会员"
      left-arrow
      @click-left="$router.back()"
    />
    
    <!-- 会员卡片 -->
    <div class="member-card">
      <div class="card-content">
        <div class="user-info">
          <span class="username">{{ userInfo.username || '游客' }}</span>
          <span class="current-level">当前等级：{{ userInfo.membership_level || '普通会员' }}</span>
        </div>
        <div class="prompt">快去开通SVIP享受更多优惠</div>
        <div class="savings">已累积为您节省 ¥0</div>
      </div>
    </div>
    
    <!-- 卡种选择 -->
    <van-cell-group>
      <van-cell title="卡种选择" class="section-title" />
      <div class="card-options">
        <van-button
          v-for="(option, index) in cardOptions"
          :key="index"
          :class="{ active: activeCard === index }"
          @click="activeCard = index"
        >
          <div class="option-title">{{ option.title }}</div>
          <div class="option-price">¥{{ option.price }}</div>
          <div class="option-save">省¥{{ option.save }}</div>
        </van-button>
      </div>
    </van-cell-group>
    
    <!-- 会员权益 -->
    <van-cell-group>
      <van-cell title="会员权益" class="section-title" />
      <div class="benefits">
        <van-cell
          v-for="(benefit, index) in benefits"
          :key="index"
          :title="benefit.title"
          :label="benefit.desc"
          class="benefit-item"
        />
      </div>
    </van-cell-group>
    
    <!-- 开通按钮 -->
    <van-button
      type="primary"
      block
      class="subscribe-btn"
      @click="handleSubscribe"
    >
      立即开通 ¥{{ selectedCardPrice }}
    </van-button>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { NavBar, Cell, CellGroup, Button, Dialog, Toast } from 'vant';
import axios from 'axios';
import { useRouter } from 'vue-router';

export default {
  components: {
    [NavBar.name]: NavBar,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Button.name]: Button
  },
  setup() {
    const router = useRouter();
    const activeCard = ref(0);
    const userInfo = ref({
      username: '',
      membership_level: ''
    });
    
    const cardOptions = ref([
      { title: '白银卡', price: '99', save: '5' },
      { title: '黄金卡', price: '199', save: '20' },
      { title: '钻石卡', price: '299', save: '52' }
    ]);
    
    const benefits = ref([
      { title: '全场包邮', desc: '享受商品包邮服务' },
      { title: '消费折扣', desc: '部分商品下单可享1折优惠' }
    ]);
    
    const selectedCardPrice = computed(() => {
      return cardOptions.value[activeCard.value].price;
    });

    // 获取会员信息
    const getMembershipInfo = async () => {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          return; // 未登录状态不获取信息
        }

        const response = await axios.get('/user/membership_info', {
          headers: { 
            'Authorization': `Bearer ${token}`
          }
        });

        if (response.data) {
          userInfo.value = {
            username: response.data.username || '用户',
            membership_level: response.data.current_membership?.name || '普通会员'
          };
        }
      } catch (error) {
        console.error('获取会员信息失败:', error);
      }
    };

    onMounted(async () => {
      await getMembershipInfo();
    });
    
    const handleSubscribe = () => {
      const token = localStorage.getItem('token');
      if (!token) {
        Toast('请先登录');
        router.push('/login');
        return;
      }

      Dialog.confirm({
        title: '开通确认',
        message: `确认开通${cardOptions.value[activeCard.value].title}会员？`,
      }).then(async () => {
        try {
          // 调用开通会员接口
          const response = await axios.post(
            '/user/consume_and_upgrade',
            {
              amount: Number(cardOptions.value[activeCard.value].price),
              description: `开通${cardOptions.value[activeCard.value].title}会员`
            },
            {
              headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
              }
            }
          );
          
          if (response.data.success) {
            Toast('会员开通成功');
            await getMembershipInfo(); // 刷新会员信息
          } else {
            Toast(`开通失败：${response.data.message}`);
          }
        } catch (error) {
          console.error('开通会员失败:', error);
          Toast('开通会员失败，请稍后重试');
        }
      });
    };
    
    return {
      activeCard,
      cardOptions,
      benefits,
      selectedCardPrice,
      handleSubscribe,
      userInfo
    };
  }
};
</script>

<style scoped>
.member-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 50px;
}

/* 会员卡片样式 */
.member-card {
  background-color: #fdebd0;
  margin: 15px;
  border-radius: 12px;
  padding: 20px;
}

.user-info {
  margin-bottom: 15px;
}

.username {
  font-size: 16px;
  font-weight: bold;
  margin-right: 15px;
}

.current-level {
  font-size: 14px;
  color: #666;
  background-color: rgba(179, 135, 75, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
}

.prompt {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}

.savings {
  font-size: 14px;
  color: #b3874b;
  text-align: center;
  padding: 10px;
  background-color: rgba(179, 135, 75, 0.1);
  border-radius: 8px;
}

/* 卡种选择样式 */
.section-title {
  font-weight: bold;
}

.section-title::after {
  content: "";
  position: absolute;
  left: 16px;
  right: 16px;
  bottom: 0;
  height: 1px;
  background-color: #f5f5f5;
}

.card-options {
  display: flex;
  padding: 0 15px 15px;
  gap: 10px;
}

.card-options .van-button {
  flex: 1;
  height: auto;
  padding: 12px 0;
  border-radius: 8px;
  background-color: #fff;
  border: 1px solid #eee;
}

.card-options .van-button.active {
  border-color: #ff9500;
  background-color: #fffaf0;
}

.option-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.option-price {
  font-size: 14px;
  color: #ff5e3a;
  font-weight: bold;
  margin-bottom: 3px;
}

.option-save {
  font-size: 12px;
  color: #999;
}

/* 会员权益样式 */
.benefits {
  padding: 0 15px;
}

.benefit-item {
  margin-bottom: 10px;
  border-radius: 8px;
  overflow: hidden;
}

.benefit-item .van-cell__title {
  font-weight: bold;
}

/* 开通按钮样式 */
.subscribe-btn {
  margin: 0px 15px 0;
  background: linear-gradient(to right, #ff9500, #ff5e3a);
  border: none;
  border-radius: 8px;
  height: 48px;
  font-size: 16px;
  font-weight: bold;
  box-shadow: 0 4px 10px rgba(255, 149, 0, 0.3);
}
</style>